<?php
require_once('includes/bootstrap.php');
	
if (empty($_SESSION[SESSION_NAME]))
{
	header("HTTP/1.0 404 Not Found");
	exit;
}

$clientId = filter_input(INPUT_GET, 'client_id', FILTER_SANITIZE_NUMBER_INT);
$client = false;

if (!empty($clientId))
{
	$req = mysql_query("SELECT clients.* FROM clients WHERE id=$clientId LIMIT 1");
	$row = mysql_fetch_assoc($req);
	
	if (!empty($row))
		$client = ' ' . $row['firstname'] . ' ' . $row['name'];
}

?>

<html>
	<head>
		<?php include_once('includes/head.php'); ?>
	</head>

	<body>

		<?php include_once('includes/menu_admin.php'); ?>

		<h1>Commandes <?= $client ?></h1>

		<table class="display dataTable">
			<thead>
				<tr>
					<th>ID commande</th>
					<th>Client</th>
					<th>Date</th>
					<th>Prix</th>
					<th>Détail commande</th>
				</tr>
			</thead>

			<tbody>
				<?php
				
				$clientSql = "";
				if (!empty($clientId))
					$clientSql = " AND clients.id=" . $clientId;
				
				$req = mysql_query("
SELECT clients.name, clients.firstname, orders.id, orders.price, orders.date, GROUP_CONCAT(IF(quantity=1, items.name, CONCAT(items.name, ' (x', quantity, ')')) SEPARATOR \"\n\") as 'items'
FROM orders
INNER JOIN clients ON clients.id = orders.client_id
INNER JOIN order_items ON orders.id = order_items.order_id
INNER JOIN items ON items.id = order_items.item_id
WHERE 1=1
	$clientSql
GROUP BY orders.id
ORDER BY DATE ASC");

				$i=0;

				while ($row = mysql_fetch_assoc($req))
				{
					if ($i%2 == 0)
						echo '<tr class="gradeA even">';
					else
						echo '<tr class="gradeA odd">';

					echo '	<td>' . $row['id'] . '</td>';
					echo '	<td>' . $row['name'] . ' ' . $row['firstname'] . '</td>';
					echo '	<td>' . $row['date'] . '</td>';
					echo '	<td>' . $row['price'] . ' €</td>';
					echo '	<td>' . nl2br($row['items']) . '</td>';
					echo '</tr>';

					$i++;
				}

				?>
			</tbody>

		</table>

		<script type="text/javascript">
			$('table').dataTable({
				"iDisplayLength": 20,
				"bJQueryUI": true
			});
		</script>

	</body>

</html>
